#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define MEM_PART "/proc/meminfo"


//用于存储内存信息的结构体
struct mem_info
{
    char MemTotal[20];
    char MemFree[20];
    char MemAvailable[20];
    char Buffers[20];
    char Cached[20];

};

typedef struct mem_info MEM_info,*pMEM_info;

 

int get_file_line(char *result,char *fileName,int lineNumber)
{
    FILE *filePointer;
    int i=0;
    char buffer[256];

    if((fileName==NULL)||(result==NULL))
    {
        return 0;
    }

    if(!(filePointer=fopen(fileName,"rb")))
    {return 0;}


    while((!feof(filePointer))&&(i<lineNumber))
    {
        if(!fgets(buffer,256,filePointer))
        {
            return 0;
        }
        i++;
    }



    strcpy(result,buffer);

    if(0!=fclose(filePointer))
    {
        return 0;
    }

    return 1;
}



//按行读取/proc/meminfo中的信息，并保存到mem结构体中
int get_mem_info(pMEM_info mem)
{
    char buffer[300];
    if(NULL==mem)
    {
        printf("\nget_mem_info:param null!\n");
        return 0;
    }
    memset(mem,0,sizeof(MEM_info));
    if(1==get_file_line(buffer,MEM_PART,1))//读取第一行
    {
        sscanf(buffer,"%*s %s",mem->MemTotal);
        if(1==get_file_line(buffer,MEM_PART,2))//读取第二行
        {   sscanf(buffer,"%*s %s",mem->MemFree);
            if(1==get_file_line(buffer,MEM_PART,3))//读取第三行
            {   sscanf(buffer,"%*s %s",mem->MemAvailable);
                if(1==get_file_line(buffer,MEM_PART,4))//读取第四行
                    {   sscanf(buffer,"%*s %s",mem->Buffers);
                        if(1==get_file_line(buffer,MEM_PART,5))//读取第五行
                            {
                                sscanf(buffer,"%*s %s",mem->Cached);
                                return 1;
                            }

                    }

            }

        }

    }

    return 0;
}


int main()
{
    
    MEM_info mem;

    get_mem_info(&mem);
    printf("\n MemTotal:%s MemFree:%s MemAvailable:%s Buffers:%s Cached:%s\n",mem.MemTotal,mem.MemFree,mem.MemAvailable,mem.Buffers,mem.Cached);
    return 1;

}
